$().ready(function () {
    $('.summernote').summernote({
        height: '300px',
        lang: 'zh-CN',
        callbacks: {
            onImageUpload: function (files, editor, $editable) {
                sendFile(files);
            }
        }
    });
    validateRule();
    initSelect();
});

$.validator.setDefaults({
    submitHandler: function () {
        save();
    }
});

function imgIds() {
    var imgIds = "";
    $("input[name='imgId']").each(function (i) {
        if (0 == i) {
            imgIds = $(this).val();
        } else {
            imgIds += ("," + $(this).val());
        }
    });
    return imgIds;
}

function checkImg() {
    var imgFlag = true;
    $("input[name='imgId']").each(function (i) {
        if ($(this).val() == '') {
            imgFlag = false;
            return;
        }
    });
    return imgFlag;
}

function save() {
    var details_sn = $("#details_sn").summernote('code');
    $("#details").val(details_sn);
    $("#imgIds").val(imgIds());
    if (!checkImg()) {
        layer.msg("请上传商品主图");
        return;
    }
    $.ajax({
        cache: true,
        type: "POST",
        url: "/product/manager/save",
        data: $('#signupForm').serialize(),// 你的formid
        async: false,
        error: function (request) {
            parent.layer.alert("Connection error");
        },
        success: function (data) {
            if (data.code == 0) {
                parent.layer.msg("操作成功");
                parent.reLoad();
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
            } else {
                parent.layer.alert(data.msg);
            }
        }
    });
}

function validateRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#signupForm").validate({
        rules: {
            name: {
                required: true,
                maxlength: 25
            },
            categoryId: {
                required: true
            },
            summary: {
                maxlength: 50
            },
            price: {
                required: true
            },
            stock: {
                required: true
            }
        },
        messages: {
            name: {
                required: icon + "请输入商品名称",
                maxlength: $.validator.format("商品名称不能大于{0}个字符")
            },
            categoryId: {
                required: icon + "请选择商品分类"
            },
            summary: {
                required: icon + "请输入商品名称",
                maxlength: $.validator.format("商品名称不能大于{0}个字符")
            },
            price: {
                required: icon + "请输入商品价格"
            },
            stock: {
                required: icon + "请输入库存量"
            }
        }
    });
}

function initSelect() {
    //绑定Ajax的内容
    $.getJSON('/category/list_product', function (data) {
        $.each(data, function (i, item) {
            $("#categoryId").append("<option value='" + item.id + "'>&nbsp;" + item.name + "</option>");
        });
    });
}

//编辑器新增的ajax上传图片函数
function sendFile(files, editor, $editable) {
    var size = files[0].size;
    if ((size / 1024 / 1024) > 2) {
        alert("图片大小不能超过2M...");
        return false;
    }
    var formData = new FormData();
    formData.append("file", files[0]);
    $.ajax({
        data: formData,
        type: "POST",
        url: "/image/upload",    // 图片上传出来的url，返回的是图片上传后的路径，http格式
        cache: false,
        contentType: false,
        processData: false,
        dataType: "json",
        success: function (data) {//data是返回的hash,key之类的值，key是定义的文件名
            $('.summernote').summernote('insertImage', data.fileName);
        },
        error: function () {
            alert("上传失败");
        }
    });
}

layui.use('upload', function () {
    var upload = layui.upload;
    //执行实例
    var uploadInst = upload.render({
        elem: '#imgId1Upload', //绑定元素
        url: '/image/upload',
        size: 1000,
        accept: 'file',
        done: function (r) {
            layer.msg(r.msg);
            $('#imgId1Div').empty();
            $("#imgId1").val(r.imgId);
            var _html = '<a target="_blank" href="' + r.fileName + '">\n' +
                '<img alt="image" class="feed-photo" src="' + r.fileName + '"></a>';
            $('#imgId1Div').html(_html);
        },
        error: function (r) {
            layer.msg(r.msg);
        }
    });
});

layui.use('upload', function () {
    var upload = layui.upload;
    //执行实例
    var uploadInst = upload.render({
        elem: '#imgId2Upload', //绑定元素
        url: '/image/upload',
        size: 1000,
        accept: 'file',
        done: function (r) {
            layer.msg(r.msg);
            $('#imgId2Div').empty();
            $("#imgId2").val(r.imgId);
            var _html = '<a target="_blank" href="' + r.fileName + '">\n' +
                '<img alt="image" class="feed-photo" src="' + r.fileName + '"></a>';
            $('#imgId2Div').html(_html);
        },
        error: function (r) {
            layer.msg(r.msg);
        }
    });
});

layui.use('upload', function () {
    var upload = layui.upload;
    //执行实例
    var uploadInst = upload.render({
        elem: '#imgId3Upload', //绑定元素
        url: '/image/upload',
        size: 1000,
        accept: 'file',
        done: function (r) {
            layer.msg(r.msg);
            $('#imgId3Div').empty();
            $("#imgId3").val(r.imgId);
            var _html = '<a target="_blank" href="' + r.fileName + '">\n' +
                '<img alt="image" class="feed-photo" src="' + r.fileName + '"></a>';
            $('#imgId3Div').html(_html);
        },
        error: function (r) {
            layer.msg(r.msg);
        }
    });
});

layui.use('upload', function () {
    var upload = layui.upload;
    //执行实例
    var uploadInst = upload.render({
        elem: '#imgId4Upload', //绑定元素
        url: '/image/upload',
        size: 1000,
        accept: 'file',
        done: function (r) {
            layer.msg(r.msg);
            $('#imgId4Div').empty();
            $("#imgId4").val(r.imgId);
            var _html = '<a target="_blank" href="' + r.fileName + '">\n' +
                '<img alt="image" class="feed-photo" src="' + r.fileName + '"></a>';
            $('#imgId4Div').html(_html);
        },
        error: function (r) {
            layer.msg(r.msg);
        }
    });
});
